package cn.sskxyz.security.core.config;

import cn.sskxyz.security.core.property.SecurityProperties;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.jwt.crypto.sign.RsaVerifier;
import org.springframework.security.oauth2.provider.token.DefaultTokenServices;
import org.springframework.security.oauth2.provider.token.TokenStore;
import org.springframework.security.oauth2.provider.token.store.JwtAccessTokenConverter;
import org.springframework.security.oauth2.provider.token.store.JwtTokenStore;

import java.security.KeyFactory;
import java.security.KeyPair;
import java.security.interfaces.RSAPublicKey;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
import java.util.Base64;
import java.util.Collections;

/**
 * 认证服务用来签发jwt令牌，资源服务可以使用本地配置的公钥来验证生成的token，配置类型为jwt即可
 */
@Configuration
@EnableConfigurationProperties(SecurityProperties.class)
@ConditionalOnProperty(prefix = "system.security", name = "token-type", havingValue = "jwt")
public class JwtTokenConfigure {

    @Autowired
    private SecurityProperties securityProperties;

    @Bean
    @ConditionalOnMissingBean(TokenStore.class)
    public TokenStore jwtTokenStore() throws Exception {
        JwtTokenStore tokenStore = new JwtTokenStore(jwtAccessTokenConverter());
        return tokenStore;
    }

    @Bean
    @ConditionalOnMissingBean(JwtAccessTokenConverter.class)
    public JwtAccessTokenConverter jwtAccessTokenConverter() throws Exception {
        JwtAccessTokenConverter jwtAccessTokenConverter = new JwkAccessTokenConverter(
                Collections.singletonMap("kid", securityProperties.getJwtKeyPair().getKeyId()));
        String pubKeyStr = securityProperties.getJwtKeyPair().getPublicKey();
        String priKeyStr = securityProperties.getJwtKeyPair().getPrivateKey();
        KeyFactory factory = KeyFactory.getInstance("RSA");
        byte[] bytesPub = Base64.getDecoder().decode(pubKeyStr);
        X509EncodedKeySpec publicKey = new X509EncodedKeySpec(bytesPub);
        if (priKeyStr == null) {
            RSAPublicKey rsaPublicKey = (RSAPublicKey) factory.generatePublic(publicKey);
            jwtAccessTokenConverter.setVerifier(new RsaVerifier(rsaPublicKey));
        } else {
            byte[] bytesPri = Base64.getDecoder().decode(priKeyStr);
            PKCS8EncodedKeySpec privateKey = new PKCS8EncodedKeySpec(bytesPri);
            KeyPair keyPair = new KeyPair(factory.generatePublic(publicKey), factory.generatePrivate(privateKey));
            jwtAccessTokenConverter.setKeyPair(keyPair);
        }
        jwtAccessTokenConverter.afterPropertiesSet();
        return jwtAccessTokenConverter;
    }

    @Bean
    @ConditionalOnMissingBean(DefaultTokenServices.class)
    public DefaultTokenServices tokenService() throws Exception {
        DefaultTokenServices tokenServices = new DefaultTokenServices();
        tokenServices.setTokenStore(jwtTokenStore());
        tokenServices.setTokenEnhancer(jwtAccessTokenConverter());
        tokenServices.setSupportRefreshToken(true);
        tokenServices.setAccessTokenValiditySeconds(7200);
        tokenServices.afterPropertiesSet();
        return tokenServices;
    }
}
